<!--模态框淡入淡出-->
var overflowlist=document.getElementsByClassName("overflow");
var modalbg=document.getElementsByClassName("modal_bg")[0];
var modal=document.getElementsByClassName("action_menu_container")[0];
var cancel=document.getElementById("cancel");
var timer;
for(var i=0;i<overflowlist.length;i++){
    overflowlist[i].onclick=function(){
        modalbg.style.display="block";
        modal.style.display="block";
    }
};
cancel.onclick=function(){
    if(modalbg.style.display=="block"&&modal.style.display=="block"){
        modalbg.className+=' animate_out';
        modal.className+=' animate_out';
    }
    timer=setTimeout(changeclass,100);
};
function changeclass(){
    modalbg.className='modal_bg';
    modal.className='action_menu_container';
    clearTimeout();
    timer=null;
    changedisplay();
};
function changedisplay(){
    modalbg.style.display="none";
    modal.style.display="none";
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//var regid=/(id=)([a-zA-Z0-9]*)/;
//var urlfrom=window.location.href;
//var id = urlfrom.match(regid).splice("=")[2];
var id= $.cookie("MYID");
if(/\?id=[0-9a-zA-Z]+/.test(location.href)){
    id=(location.href).match(/id=[0-9a-zA-Z]+/)[0].split("=")[1];
}
//问答
document.getElementById("question1").onclick=function(){
    location.href="weixin/questionlisttw.html";
};
//编辑资料 页面跳转
document.getElementById("bjzl").onclick=function(){

    location.href="mysetpage.html";
};
//屏蔽管理 页面跳转
$("#pbgl").click(function(){
    location.href="shieldpage.html";
});
//个人账户
document.getElementById("myscore").onclick=function(){
    location.href="scoredetial.html";
};
//我的问题 页面跳转
$("#myaskbtn").click(function(){
    location.href="https://www.pulu.com/weixin/myquestionlist.html";
});
//我的回答 页面跳转
$("#myanswerbtn").click(function(){
    location.href="https://www.pulu.com/weixin/myquestionlist2.html";
});
//我的经验 页面跳转
$("#myexpbtn").click(function(){
    location.href="https://www.pulu.com/weixin/myquestionlist1.html";
});
//我的收藏 页面跳转
$("#mycollectbtn").click(function(){
    location.href="https://www.pulu.com/weixin/myquestionlist5.html";
});
//退出登录
$("#signout").click(function(){
    //id="";
    //$.cookie("MYID","");
	$.cookie("issignout","退出登录");
    location.href="weixin/login.html"
});
var haveimg="no";//控制能否点击头像
//点击展开大图
//$(".photo").click(function(){
//    if(haveimg=="yes"){
//        var imgheight=$("#showimg").height();
//        var bigheight=window.screen.availHeight;
//        $("#digimgplace").height(bigheight);
//        if(bigheight>imgheight){
//            $("#showimg").css("marginTop",(bigheight-imgheight)/2);
//        }
//        $("#digimgplace").css("display","block");
//        $("#page_wrapper").css("display","none");
//    }
//});
//关闭大图
$("#digimgplace").click(function(){
    $("#digimgplace").css("display","none");
    $("#page_wrapper").css("display","block");
});
//加载中定位
var wh=window.screen.availHeight;
var marginheight=(wh-80)/2;
//$("#waitplace>div").css("marginTop",marginheight+"px");
//最新动态列表页
$("#lastinfopage").click(function(){
    $.cookie("otherid","");
    location.href="lastinfo.html";
});
//别人回复提醒 详情页
$("#answernotic div").click(function(){
    $.cookie("noticdelid","firstin");
    location.href="mynotic.html"
});
$().ready(function(){
    //获取回复动态
    $.ajax({
        type:"get",
        url:getanswernumurl+id,
        datatype:"json",
        success:function(d){
            console.log("回答动态",d);
            if(d.Data>0){
                $("#answernotic div span").html(d.Data);
                $("#answernotic").css("display","block");
                $("#newnotenotice").css("display","block");
                $("#newnotenotice").html(d.Data);
            }else{
                $("#answernotic").css("display","none");
            }
        }
    });
    //加载页面
    $.ajax({
        type: "post",
        //提交的网址
        url: userurl,
        //提交的数据
        data: { "userId": id },
        //返回数据的格式
        datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
        //成功返回之后调用的函数
        success: function (data) {
            //等待区域隐藏
            $("#waitplace").css("display","none");

            console.log(data.Data);
            $("#page_title").html(data.Data.nick);
            $("#nickname").html(data.Data.nick);
            if(data.Data.userAva){
                haveimg="yes";
                //$(".photo").append("<img class='profile_photo_img' src='https://42.62.66.198:8003/"+data.Data.userAva+"'>");
                $("#photo img").attr("src","http://42.62.66.198:8003/"+data.Data.userAva);
				$("#photo img").css("display","block");
                $("#digimgplace").css("background-image","url('http://42.62.66.198:8003/"+data.Data.userAva+"')");
            }else{
                $(".photo").append("<img class='profile_photo_img' src='img/af8.png'>");
                $("#digimgplace").css("background-image","url('https://img/af8.png')");
            }
            if(data.Data.sex===1){
                document.getElementById("sex1").style.display="inline-block";
            }else if(data.Data.sex===0){
                document.getElementById("sex2").style.display="inline-block";
            }
            $("#cover").html(data.Data.cover);
            $("#myword").html(data.Data.sign);
            if(data.Data.city&&data.Data.city.length>0){
                $("#city").html(data.Data.city);
            }
            $("#educationword").html(data.Data.education);
            var jobs="";
            if(data.Data.jobs&&data.Data.jobs.length>0){
                for(var i= 0;i<data.Data.jobs.length;i++){
                    jobs+=data.Data.jobs[i].typename+"&nbsp;&nbsp;"
                }
            }
            $("#myjobs").html(jobs);

            var news="";
            if(data.Data.news&&data.Data.news.length>0){
                for(var n= 0;n<data.Data.news.length;n++){
                    news+=data.Data.news[n].typename+"&nbsp;&nbsp;"
                }
            }
            $("#mynews").html(news);
            var hobby="";
            if(data.Data.hobbys&&data.Data.hobbys.length>0){
                for(var r= 0;r<data.Data.hobbys.length;r++){
                    hobby+=data.Data.hobbys[r].typename+"&nbsp;&nbsp;"
                }
            }
            $("#myhobby").html(hobby);
            $("#visitedcity").html(data.Data.visitedcity);
            //铺路信息
            $("#scoreword").html(Math.round(parseFloat(data.Data.score))/100+"元");
            //$("#scoreword").html(data.Data.score+"分");
            $("#myquestionCount").html(data.Data.myquestionCount+"条");
            $("#myanswerCount").html(data.Data.myanswerCount+"条");
            $("#myexpCount").html(data.Data.myexpCount+"条");
            $("#mycollecttionCount").html(data.Data.mycollecttionCount+"条");
            //陌生人可见
            if(data.Data.statusstrangesee===1){//可见
                document.getElementById("seemeimg1").style.display="none";
                document.getElementById("seemeimg2").style.display="block";
            }else if(data.Data.statusstrangesee===0){//不可见
                document.getElementById("seemeimg1").style.display="block";
                document.getElementById("seemeimg2").style.display="none";
            }
        }
    });
    //时间 几天前 几分钟前
    function getDateTimeStamp(dateStr){
        dateStr=dateStr.match(/[0-9\-T\:]+/)[0].replace(/T/g,' ');
        return Date.parse(dateStr.replace(/-/gi,"/"));
    }
    function getDateDiff(dateTimeStamp){
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - dateTimeStamp;
        if(diffValue < 0){return;}
        var monthC =diffValue/month;
        var weekC =diffValue/(7*day);
        var dayC =diffValue/day;
        var hourC =diffValue/hour;
        var minC =diffValue/minute;
        if(monthC>=1){
            result="" + parseInt(monthC) + "月前";
        }
        else if(weekC>=1){
            result="" + parseInt(weekC) + "周前";
        }
        else if(dayC>=1){
            result=""+ parseInt(dayC) +"天前";
        }
        else if(hourC>=1){
            result=""+ parseInt(hourC) +"小时前";
        }
        else if(minC>=1){
            result=""+ parseInt(minC) +"分钟前";
        }else
            result="刚刚";
        return result;
    }
    //最新动态
    //$.ajax({
    //    type:"get",
    //    datatype:"json",
    //    url:"https://www.pulu.com/webapi/api/PuluUser/GetUserStatusByUserId?userId="+id+"&currentIndex=1&pageSize=10",
    //    success:function(data){
    //        console.log("最新动态");
    //        console.log(data);
    //        for(var i=0;i<data.Data.length;i++){
    //            var score="";
    //            if(data.Data[i].score){
    //                score="<span class='scoreword'>"+data.Data[i].score+"</span>";
    //            }
    //            var des="";
    //            if(data.Data[i].des||data.Data[i].answerContent){
    //                var word=data.Data[i].des||data.Data[i].answerContent;
    //                des="<div class='desword' style='padding-bottom:5px;'>"+word+"</div>";
    //            };
    //            if(data.Data[i].contenttypeName==="经验"){
    //                var hrefto1="href=shareexppage.html?eid="+data.Data[i].contentid;
    //                var tim1=getDateDiff(getDateTimeStamp(data.Data[i].time));
    //                $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span>"+score+"<span class='rt'>"+tim1+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto1+">"+data.Data[i].content+"</a> </h2> <div class='ContentFooter QuestionFooter'> <span class='answer_count'>浏览</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div> </div> </div>");
    //            }else if(data.Data[i].contenttypeName==="问题"){
    //                var hrefto2="href=questiondetail.html?qid="+data.Data[i].contentid;
    //                var tim2=getDateDiff(getDateTimeStamp(data.Data[i].time));
    //                $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span>"+score+"<span class='rt'>"+tim2+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto2+">"+data.Data[i].content+"</a> </h2> <div class='ContentFooter QuestionFooter'> <span class='answer_count'>回答</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div> </div> </div>");
    //            }else if(data.Data[i].contenttypeName==="新闻"){
    //                var hrefto3="href="+data.Data[i].url;
    //                var tim3=getDateDiff(getDateTimeStamp(data.Data[i].time));
    //                $("#setpagenewslist").append("<div class='pagedlist_item'> <div class='feed_item feed_type_question'> <div class='EventHeader'> <span>您"+data.Data[i].operatetypeName+"了此"+data.Data[i].contenttypeName+"</span> <span class='rt'>"+tim3+"</span> </div>"+des+"<h2 class='no_highlight'> <a class='question_link'"+hrefto3+">"+data.Data[i].content+"</a> </h2> <div class='ContentFooter QuestionFooter'> <span class='answer_count'>浏览</span> <span class='answer_count'>"+data.Data[i].count+"</span> </div> </div> </div>");
    //            }
    //        }
    //    }
    //});
    //陌生人查看十条
    $("#seeme").click(function(){
        if(document.getElementById("seemeimg1").style.display==="block"){
            document.getElementById("seemeimg1").style.display="none";
            document.getElementById("seemeimg2").style.display="block";
            $.ajax({
                type:"post",
                datatype:"json",
                url:"https://www.pulu.com/webapi/api/PuluUser/OpenStrangerSee",
                data:{"userId":id},
                success:function(d){
                    console.log("陌生人看十条");
                    console.log(d);
                }
            })
        }else if(document.getElementById("seemeimg2").style.display==="block"){
            document.getElementById("seemeimg1").style.display="block";
            document.getElementById("seemeimg2").style.display="none";
            $.ajax({
                type:"post",
                datatype:"json",
                url:"https://www.pulu.com/webapi/api/PuluUser/CloseStrangerSee",
                data:{"userId":id},
                success:function(d){
                    console.log("解除陌生人看十条");
                    console.log(d);
                }
            })
        }
    });
});
//环信建立连接
var conn = new WebIM.connection({
    httpss: WebIM.config.httpss,
    url: WebIM.config.xmppURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});
//登录
var options = {
    apiUrl: WebIM.config.apiURL,
    user:id,
    pwd:id,
    appKey: "pulu#pulu"
};
conn.open(options);

var handlePresence = function ( e ) {
    //（发送者希望订阅接收者的出席信息），即别人申请加你为好友
    if ( e.type === 'subscribe' ) {
        console.log("别人加你好友2");
        $.ajax({
            type:"post",
            datatype:"json",
            url:"https://www.pulu.com/webapi/api/puluuser/getuser",
            data:{"userId": e.from},
            success:function(fd){
                //console.log("好友申请："+fd.Data.nick);
                var infor=fd.Data.nick+"&nbsp;"+"："+ e.status;
                $("#fromwho").html(infor);
                $("#friendInfor").css("display","block");
                //同意添加好友
                $("#iamagree").click(function(){
                    conn.subscribed({
                        to: e.from,
                        message : "[resp:true]"
                    });
                    //conn.subscribe({//需要反向添加对方好友
                    //    to: e.from,
                    //    message : "[resp:true]"
                    //});
                    //关闭提示框
                    $("#friendInfor").css("display","none");
                    $.ajax({
                        type:"post",
                        datatype:"json",
                        url:"https://www.pulu.com/webapi/api/PuluGoodFriend/Addpulu_goodfriend",
                        data:{"userId":e.from,"friendId":id},
                        success:function(d){
                            console.log("好友数据以保存");
                            console.log(d);
                        }
                    })
                });
                //拒绝添加好友
                $("#iampass").click(function(){
                    conn.unsubscribed({
                        to: e.from,
                        message : "拒绝"
                    });
                    $("#friendInfor").css("display","none");
                })
            }
        });
        console.log(e);
        //若e.status中含有[resp:true],则表示为对方同意好友后反向添加自己为好友的消息，demo中发现此类消息，默认同意操作，完成双方互为好友；如果不含有[resp:true]，则表示为正常的对方请求添加自己为好友的申请消息。
    }
    //(发送者允许接收者接收他们的出席信息)，即别人同意你加他为好友
    if ( e.type === 'subscribed' ) {
        console.log("别人同意了你的好友请求");
        console.log(e);
        $.ajax({
            type:"post",
            datatype:"json",
            url:"https://www.pulu.com/webapi/api/puluuser/getuser",
            data:{"userId": e.from},
            success:function(d){
                var infor=d.Data.nick+"&nbsp;"+"同意了您的好友请求";
                $("#iamagree2").html(infor);
                $("#friendInfor2").css("display","block");
                $("#iknow2").click(function(){
                    $("#friendInfor2").css("display","none");
                })
            }
        });
    }
    //（发送者取消订阅另一个实体的出席信息）,即删除现有好友
    if ( e.type === 'unsubscribe' ) {
        console.log("删除好友");
        console.log(e);
    }
    //（订阅者的请求被拒绝或以前的订阅被取消），即对方单向的删除了好友
    if ( e.type === 'unsubscribed' ) {
        console.log("你的好友请求被拒绝");
        console.log(e);
        $.ajax({
            type:"post",
            datatype:"json",
            url:"https://www.pulu.com/webapi/api/puluuser/getuser",
            data:{"userId": e.from},
            success:function(d){
                var infor=d.Data.nick+"&nbsp;"+"拒绝了您的好友请求";
                $("#iamagree2").html(infor);
                $("#friendInfor2").css("display","block");
                $("#iknow2").click(function(){
                    $("#friendInfor2").css("display","none");
                })
            }
        });
    }
};
conn.listen({
    onPresence: function ( message ) {
        handlePresence(message);
    },//收到联系人订阅请求、处理群组、聊天室被踢解散等消息
    onOpened: function ( message ) {          //连接成功回调
        //如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
        conn.setPresence();
        console.log("与环信连接成功");
        console.log("开始调用好友列表");
        conn.getRoster({
            success: function ( roster ) {
                //获取好友列表，并进行好友列表渲染，roster格式为：
                /** [
                 {
                   jid:"asemoemo#chatdemoui_test1@easemob.com",
                 name:"test1",
                 subscription: "both"
                 }
                 ]
                 */
                console.log("完成");
                for ( var i = 0, l = roster.length; i < l; i++ ) {
                    var ros = roster[i];
                    //ros.subscription值为both/to为要显示的联系人，此处与APP需保持一致，才能保证两个客户端登录后的好友列表一致
                    if ( ros.subscription === 'both' || ros.subscription === 'to' ) {
                        console.log(ros);
                    }
                }
            },
            error:function(d){
                console.log(d);
            }
        });
        console.log("结束调用好友列表");
    },
    onClosed: function ( message ) {console.log("1");},         //连接关闭回调
    onEmojiMessage: function ( message ) {console.log("2");},   //收到表情消息
    onPictureMessage: function ( message ) {console.log("3");}, //收到图片消息
    onCmdMessage: function ( message ) {console.log("4");},     //收到命令消息
    onAudioMessage: function ( message ) {console.log("5");},   //收到音频消息
    onLocationMessage: function ( message ) {console.log("6");},//收到位置消息
    onFileMessage: function ( message ) {console.log("7");},    //收到文件消息
    onVideoMessage: function ( message ) {console.log("8");},   //收到视频消息
    onRoster: function ( message ) {console.log("10");},         //处理好友申请
    onInviteMessage: function ( message ) {console.log("11");},  //处理群组邀请
    onOnline: function () {console.log("12");},                  //本机网络连接成功
    onOffline: function () {console.log("13");},                 //本机网络掉线
    onError: function ( message ) {console.log("14");}           //失败回调
});
//拒绝提醒框关闭
$("#ikonw2").click(function(){
    $("#friendInfor2").css("display","none");
});